package cn.yunhe.java.controller;

import cn.hutool.crypto.SecureUtil;
import cn.yunhe.java.object.AjaxDone;
import cn.yunhe.java.security.user.MyPrincipal;
import cn.yunhe.java.service.LoginService;
import cn.yunhe.java.pojo.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private LoginService service;

//    @RequestMapping("login")
//    public String login(String username, String password,
//                        String verifyCode, Model model,HttpServletRequest request){
//        if(StringUtils.isEmpty(username)){
//            model.addAttribute("msg","请输入用户名！");
//            return "../../login";
//        }
//
//        if(StringUtils.isEmpty(password)){
//            model.addAttribute("msg","请输入密码！");
//            return "../../login";
//        }
//
//        if(StringUtils.isEmpty(verifyCode)){
//            model.addAttribute("msg","请输入验证码！");
//            return "../../login";
//        }
//
//        //验证码是否正确
//        String sessionVerifyCode =(String)request.getSession().getAttribute("verifyCode");
//        if(!verifyCode.equalsIgnoreCase(sessionVerifyCode)){
//            model.addAttribute("msg","验证码错误！");
//            model.addAttribute("username",username);
//            model.addAttribute("password",password);
//
//            return "../../login";
//        }
//        //访问数据库
//         SysUser su = service.findByLoginName(username);
//        if(su==null){
//            model.addAttribute("msg","用户不存在！");
//            model.addAttribute("username",username);
//
//            return "../../login";
//        }
//
//         String dbPassword = su.getPassword();
//         String encodePassword =  SecureUtil.sha256(password) ; //加密算法
//
//         if(!dbPassword.equals(encodePassword)){
//             model.addAttribute("msg","密码错误！");
//             model.addAttribute("username",username);
//             return "../../login";
//         }
//         //登录成功
//         request.getSession().setAttribute("loginUser",su);
//
//        return "main";
//    }

    /**
     * 首页
     * @return
     */
    @RequestMapping("home")
    public String home(){
        return "home";
    }

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("index")
    public String loginPage(){
        return "../../login";
    }

    /**
     * 主页面
     * @return
     */
    @RequestMapping("main")
    public String main(){
        return "main";
    }
    /**
     * 查询菜单信息
     * @return
     */
    @RequestMapping("init")
    @ResponseBody
    public Map<String,Object> initMenu(HttpServletRequest request){
        //查询出来的是全部的菜单信息
        //需要根据用户的权限信息，来查询用户拥有菜单
        //SysUser su = (SysUser) request.getSession().getAttribute("loginUser");

       MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       SysUser su = principal.getSysUser();
       Map<String,Object> menuMap = service.queryMenu(su.getId());
       return menuMap;
    }

    /**
     * 退出
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        return "../../login";
    }

    /**
     * 到修改密码页面
     * @return
     */
    @RequestMapping("toUpdPassword")
    public String toUpdPassword(){
        return "updPassword";
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping("updPassword")
    @ResponseBody
    public AjaxDone doUpdatePassword(String oldPassword,String newPassword,String confirmPassword,HttpServletRequest request){
        MyPrincipal principal = (MyPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser su = principal.getSysUser();
        if(StringUtils.isEmpty(oldPassword)){
            return new AjaxDone(300,"请输入原始密码！");
        }

        if(StringUtils.isEmpty(newPassword)){
            return new AjaxDone(300,"请输入新密码！");
        }

        if(StringUtils.isEmpty(newPassword)){
            return new AjaxDone(300,"请输入确认密码！");
        }

        if(!SecureUtil.sha256(oldPassword).equals(su.getPassword())){
            return new AjaxDone(300,"原始密码错误！");
        }

        if(!newPassword.equals(confirmPassword)){
            return new AjaxDone(300,"两次密码不一致！");
        }

        try{
            int rst = service.updatePassword(su.getId(),SecureUtil.sha256(newPassword));
            if(rst>0)
              return new AjaxDone(200,"密码修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxDone(300,"密码修改失败！");
        }
        return new AjaxDone(300,"系统繁忙请稍后重试！");
    }

    /**
     * 验证码生成
     */
    @RequestMapping("verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int width = 80; // 图片的宽度
        int height = 30;// 图片的高度
        /*
         * 绘图
         */
        // step1,创建一个内存映像对象(画板)
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // step2,获得画笔
        Graphics g = image.getGraphics();
        // step3,给笔上色
        Random r = new Random();
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        // step4,给画板设置背景颜色
        g.fillRect(0, 0, width, height);
        // step5,绘制一个随机的字符串
        String characters="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //String number = r.nextInt(99999) + "";
        String number = "";
        for(int i=1;i<=4;i++) {
            number+=characters.charAt(r.nextInt(62));
        }
        g.setColor(new Color(0, 0, 0));
        // new Font(字体,风格,大小)
        g.setFont(new Font(null, Font.ITALIC, 24));
        g.drawString(number, 5, 25);
        // step6,加一些干扰线
        for (int i = 0; i < 8; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        /*
         * 压缩图片并输出到客户端(浏览器)
         */
        request.getSession().setAttribute("verifyCode", number);
        response.setContentType("image/jpeg");
        OutputStream ops = response.getOutputStream();
        javax.imageio.ImageIO.write(image, "jpeg", ops);
        ops.close();
    }
}
